import { defineStore } from 'pinia'
import { ensureConnected, subscribe, sendMessage as wsSend } from '@/utils/chatWs'

const KEFU_ROUTE = '/kefu'

export default defineStore('chat', {
  state: () => ({
    unreadCount: 0,
    connected: false,
    initialized: false,
  }),
  actions: {
    init(router) {
      if (this.initialized) return
      this.initialized = true
      ensureConnected()
      subscribe((evt) => {
        if (evt.type === 'open') this.connected = true
        if (evt.type === 'close') this.connected = false
        if (evt.type === 'message') {
          const isOnKefu = router && router.currentRoute.value.path.startsWith(KEFU_ROUTE)
          if (!isOnKefu) this.unreadCount += 1
        }
      })
    },
    clearUnread() { this.unreadCount = 0 },
    send(text) { return wsSend(text) }
  }
})